package com.example.demo.consumer;


import com.example.demo.bean.Order;
import com.example.demo.service.impl.MQServiceImpl;
import com.example.demo.service.OrderService;
import com.example.demo.untils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component
@RocketMQMessageListener(topic = "order",consumerGroup = "order-consumer-group")
public class MessageConsumer implements RocketMQListener<Order> {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    MQServiceImpl mqServiceImpl;

    @Autowired
    OrderService orderService;


    @Override
    public void onMessage(Order order) {
//
        //处理订单消息
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String currentTime = sdf.format(new Date());
        //统计订单信息 + 1
        //先判断key存不存在
        String value = (String) redisUtil.hget(currentTime,order.getMerchantId());
        if(value != null){
            redisUtil.hincr(currentTime,order.getMerchantId(),1);
        }else {
            //看看是不是原子
            redisUtil.hset(currentTime, order.getMerchantId(), 1);
        }
        //存入流水表
        orderService.save(order);

        //todo 判断id是不是热点账户 set
        if(redisUtil.get(order.getMerchantId()) != null){
            mqServiceImpl.asyncSendOrderlyMsg("hotAccount","", Integer.parseInt(order.getMerchantId()),"");
        }else {
            mqServiceImpl.asyncSendOrderlyMsg("commonAccount","", Integer.parseInt(order.getMerchantId()),"");
        }
    }


}
